<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="/common/template :: header(~{::title},~{::link},~{::style})">
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .closeIcon {
            width: 20px;
            height: 20px;
            position: absolute;
            right: 0;
            cursor: pointer;
        }

        .rotationChartImgDiv {
            position: relative;
            display: inline-block;

        }

        #rotationChartImgList {
            margin-left: 110px;
        }

        .rotationChartImg {
            width: 70px;
            height: 70px;
            border: 1px solid #b4b2b2;
            padding: 7px;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #009688;
        }
    </style>
</head>
<body>
<div class="layui-tab-content">

    <div>
        <div class="layui-input-inline" style="width: 300px;margin-right: 10px">
            <input type="text" id="integralMallServiceName" placeholder="服务名称" autocomplete="off"
                   class="layui-input">
        </div>
        <div class="layui-input-inline">
            <button type="submit" class="layui-btn" id="integralMallServiceSearch">搜索</button>
        </div>
        <div class="layui-input-inline" style=" float: right;margin-right: 10%;">
            <button type="submit" class="layui-btn layui-btn-normal" id="integralMallServiceAdd">添加</button>
        </div>
    </div>
    <table class="layui-hide" id="integralMallServiceTable" lay-filter="integralMallServiceTable"></table>
</div>

<input type="file" id="file" hidden="hidden" disabled>
</body>


<script th:replace="/common/template :: script"></script>
<script type="text/javascript" src="/js/wangEditor.js"></script>

<script type="text/html" id="integralMallServiceInfo">
    <form class="layui-form" style="white-space:nowrap!important;margin-top: 20px;margin-right: 20px"
          lay-filter="integralMallServiceInfoForm">
        <input name="imsId" id="imsId" hidden="hidden">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>活动券:</label>
            <div class="layui-input-block">
                <button type="button" class="layui-btn" id="selectActivityTicket">选择活动券</button>
                <input type="text" id="atId" name="atId" placeholder="活动券" style="display: none" autocomplete="off"
                       class="layui-input" lay-verify="required">
            </div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>购买须知:</label>
            <div class="layui-input-block">
                <input type="text" lay-verify="required" id="imsNotice" name="imsNotice" placeholder="购买须知"
                       autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>轮播图:</label>
            <!--            <div class="layui-upload" style="margin-left: 35px;">-->
            <div>
                <button type="button" class="layui-btn" id="rotationChartImgBtn">上传轮播图</button>
                <span>第一张为主图</span>
            </div>
            <div class="layui-upload-list" id="rotationChartImgList">
                <!--                    <div class="rotationChartImgDiv">-->
                <!--                        <img src="/images/close.png" class="closeIcon">-->
                <!--                        <img src="/images/char-ccmiao.png" class="rotationChartImg">-->
                <!--                    </div>-->
            </div>
        </div>
        <!--        </div>-->
        <div class="layui-form-item">
            <label class="layui-form-label">详情:</label>
            <div class="layui-input-block">
                <div id="editor">
                </div>
            </div>
        </div>

        <div class="layui-form-item" id="integralMallServiceInfoBtn" style="margin-left: 110px;">
            <button type="button" class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn" id="saveBtn">保存
            </button>
            <button type="button" class="layui-btn layui-btn-primary" id="closeBtn">取消</button>
        </div>


    </form>
</script>

<script type="text/html" id="integralMallServiceEdit">
    <a class="layui-btn layui-btn-xs" lay-event="updateBtn">修改</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delBtn">删除</a>
</script>


<script type="text/html" id="integralActivityTicket">
    <div class="layui-tab-content">
        <table class="layui-hide" id="integralActivityTicketTable" lay-filter="integralActivityTicketTable"></table>
    </div>
</script>
<script type="text/html" id="SelectActivityTicketEdit">
    <a class="layui-btn layui-btn-xs" lay-event="selected" id="selected">选择</a>
</script>
<script th:inline="javascript">
    layui.use(['element', 'table', 'form', 'jquery', 'upload'], function () {
        var element = layui.element;
        var table = layui.table;
        var $ = layui.jquery;
        var upload = layui.upload;
        var form = layui.form;
        var IntegralMallServiceFromWindows;
        var rotationChartImgFiles = new Array();
        var defaultFile = new File([document.getElementById("file").files[0]], "default");
        setRotationChartImgFiles()

        function setRotationChartImgFiles() {
            for (let i = 0; i < 5; i++) {
                rotationChartImgFiles[i] = {
                    file: defaultFile,
                    status: 0,
                    isExist: false
                }
            }
        }

        var imgIndex = 0;
        table.render({
            elem: '#integralMallServiceTable'
            , url: '/integralMall'
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[
                {field: 'serviceName', title: '服务名称', align: 'center'} //width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
                , {field: 'serviceTypeName', title: '服务类型', align: 'center'}
                , {field: 'integral', title: '所需积分', align: 'center'}
                , {title: '操作', align: 'center', toolbar: '#integralMallServiceEdit'}
            ]]
            , page: true
        });
        //修改
        table.on('tool(integralMallServiceTable)', function (obj) {
            // console.log(obj.data)
            if (obj.event === 'updateBtn') {
                showIntegralMallServiceFrom(obj.data);
            } else if (obj.event === 'delBtn') {
                del(obj);
            }
        })


        // 删除
        function del(obj) {
            var y = $(window).height() - window.screen.height / 2;
            layer.confirm('确定要删除吗？', {
                offset: y,
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                $.ajax({
                    url: '/integralMall/' + obj.data.imsId,
                    method: 'Post',
                    data: {_method: 'DELETE'},
                    success: function (res) {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                            obj.del();
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }
                })
            });
        }

        $('#integralMallServiceAdd').click(function () {
            showIntegralMallServiceFrom();
        })

        //搜索
        $('#integralMallServiceSearch').click(function () {
            var searchName = $('#integralMallServiceName').val();
            table.reload('integralMallServiceTable', {where: {serviceName: searchName}})
        })

        function showIntegralMallServiceFrom(data) {
            IntegralMallServiceFromWindows = layer.open({
                type: 1,
                area: ['650px', '550px'],
                maxmin: true,
                title: data ? '修改服务' : '新增服务',
                content: $('#integralMallServiceInfo').html(),
                success: function () {
                    setRotationChartImgFiles()
                    imgIndex = 0;
                    //多图片上传
                    upload.render({
                        elem: '#rotationChartImgBtn'
                        // , bindAction: '#test9'
                        // , url: 'https://httpbin.org/post' //改成您自己的上传接口
                        , multiple: true
                        , auto: false				//不自动上传设置
                        , choose: function (obj) {
                            //预读本地文件示例，不支持ie8
                            obj.preview(function (index, file, result) {
                                //只能显示5张图
                                if (imgIndex >= 5) {
                                    return;
                                }
                                //获取最后一张轮播图

                                //判断图片是否在数据库中存在
                                if (rotationChartImgFiles[imgIndex].isExist) {
                                    //存在将状态改为修改  status = 1
                                    rotationChartImgFiles[imgIndex].file = file
                                    rotationChartImgFiles[imgIndex].status = 1
                                } else {
                                    //不存在直接添加
                                    rotationChartImgFiles[imgIndex].file = file;
                                }

                                imgIndex += 1;
                                $('#rotationChartImgList').append('<div class="rotationChartImgDiv">\n' +
                                    '                        <img src="/images/close.png" class="closeIcon">\n' +
                                    '                        <img src="' + result + '" alt="' + file.name + '" class="rotationChartImg">\n' +
                                    '                    </div>')
                            });
                        }
                    });

                    //显示轮播图
                    if (data) {
                        $.ajax({
                            url: '/rotationChat/' + data.imsId,
                            method: 'get',
                            success: function (res) {
                                for (let i = 0; i < res.data.length; i++) {
                                    rotationChartImgFiles[i].isExist = true;
                                    imgIndex++;
                                    $('#rotationChartImgList').append('<div class="rotationChartImgDiv">\n' +
                                        '                        <img src="/images/close.png" class="closeIcon">\n' +
                                        '                        <img src="' + res.data[i].rcAddress + '"  class="rotationChartImg">\n' +
                                        '                    </div>')
                                }
                            }
                        })
                    }

                    //下拉框
                    $.ajax({
                        url: '/service/type/integralMallType',
                        method: 'get',
                        success: function (res) {
                            for (let i = 0; i < res.data.length; i++) {
                                if (data && data.serviceTypeId == res.data[i].serviceTypeId) {
                                    $('#serviceTypeId').append(" <option selected value=\"" + res.data[i].serviceTypeId + "\">" + res.data[i].serviceTypeName + "</option>")
                                } else {
                                    $('#serviceTypeId').append(" <option value=\"" + res.data[i].serviceTypeId + "\">" + res.data[i].serviceTypeName + "</option>")
                                }
                            }
                            //渲染select
                            layui.form.render('select');
                        }
                    })

                    //监听图片右上角 关闭按钮
                    $('#rotationChartImgList').on('click', '.closeIcon', function () {
                        // console.log($(this).parent().index())
                        var index = $(this).parent().index();
                        $(this).parent().remove();
                        imgIndex--;
                        if (rotationChartImgFiles[index].isExist) {
                            var i = index;
                            while (i < 5) {
                                if (rotationChartImgFiles[i].status != 2) {
                                    rotationChartImgFiles[i].status = 2
                                    break;
                                }
                                i++;
                            }
                            if (index !== imgIndex) {
                                rotationChartImgFiles[imgIndex].isExist = false
                            }
                        } else {
                            rotationChartImgFiles[imgIndex].file = defaultFile
                        }
                    })
                    $('#selectActivityTicket').click(function (e) {
                        selectActivityTicket();
                    })

                    //富文本编辑器
                    const E = window.wangEditor
                    const editor = new E('#editor')
                    editor.config.width = 200
                    // 或者 const editor = new E(document.getElementById('div1'))
                    // 配置 server 接口地址
                    editor.config.uploadImgServer = '/editorUploadImg'
                    editor.create()
                    editor.txt.html(data ? data.imsContent : '')
                    // editor.config.uploadImgHooks = {
                    //     customInsert: function (insertImgFn, result) {
                    //         // result 即服务端返回的接口
                    //         console.log('customInsert', result)
                    //         debugger
                    //         // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
                    //         insertImgFn(result.data[0])
                    //     }
                    // }

                    form.val('integralMallServiceInfoForm', data);
                    if (data && data.serviceName) {
                        $('#selectActivityTicket').text(data.serviceName);
                    }

                    form.on('submit(saveBtn)', function (formData) {
                        if (imgIndex <= 0) {
                            layer.msg("至少要有一张轮播图", {icon: 2});
                            return false;
                        }
                        layer.load(2);
                        // console.log(rotationChartImgFiles)
                        var form = new FormData();
                        for (let i = 0; i < rotationChartImgFiles.length; i++) {
                            form.append("files", rotationChartImgFiles[i].file);
                            form.append("status", rotationChartImgFiles[i].status);
                        }
                        form.append("imsId", formData.field.imsId);
                        form.append("atId", formData.field.atId);
                        form.append("imsNotice", formData.field.imsNotice);
                        var html = editor.txt.html();
                        // html = html.replace(/^http:\/\/[^/]+/, "");
                        form.append("imsContent", html);
                        $.ajax({
                            url: '/integralMall',
                            method: data ? 'Put' : 'Post',
                            data: form,
                            // 告诉jQuery不要去处理发送的数据
                            processData: false,
                            // 告诉jQuery不要去设置Content-Type请求头
                            contentType: false,
                            success: function (res) {
                                layer.closeAll();
                                if (res.code == 200) {
                                    layer.msg(res.msg, {icon: 1});
                                    table.reload('integralMallServiceTable')
                                } else {
                                    layer.msg(res.msg, {icon: 2});
                                }
                            }
                        })
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                    $('#closeBtn').click(function () {
                        layer.close(IntegralMallServiceFromWindows);
                    })
                }
            })
        }


        function selectActivityTicket() {
            var index = layer.open({
                type: 1,
                area: ['750px', '600px'],
                maxmin: true,
                title: '选择活动券',
                content: $('#integralActivityTicket').html(),
                success: function () {
                    table.render({
                        elem: '#integralActivityTicketTable'
                        , url: '/activityTicket'
                        , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                        , cols: [[
                            {field: 'atName', title: '活动券名称', align: 'center'} //width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
                            , {field: 'atCount', title: '数量', align: 'center'}
                            , {field: 'atReceivedCount', title: '已发放数量', align: 'center'}
                            , {
                                field: 'atUserType', title: '用户类型', align: 'center', templet: function (d) {
                                    var str = '';
                                    var state = d.atUserType;
                                    if (state == 1) {
                                        str = "<div>所有用户</div>"
                                    } else if (state == 2) {
                                        str = "<div>新用户</div>"
                                    } else if (state == 3) {
                                        str = "<div>指定用户</div>"
                                    }
                                    return str;
                                }
                            }
                            , {title: '操作', align: 'center', toolbar: '#SelectActivityTicketEdit'}
                        ]]
                        , page: true
                    });


                    table.on('tool(integralActivityTicketTable)', function (obj) {
                        console.log(obj.data);
                        console.log(obj.event);
                        if (obj.event === 'selected') {
                            $('#atId').val(obj.data.atId);
                            $('#selectActivityTicket').text(obj.data.atName);
                            layer.close(index);
                        }
                    })
                }
            })
        }
    })
</script>
</html>
